package  
{
	import flare.basic.*;
	import flare.collisions.*;
	import flare.core.*;
	import flare.primitives.*;
	import flare.system.*;
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	
	[SWF(frameRate = 120, backgroundColor = 0x808080, width = 800, height = 600 )]
	
	/**
	 * ...
	 * @author Ariel Nehmad
	 */
	public class Test12_MousePaint_Extended extends Sprite 
	{
		private var scene:Scene3D;
		private var mouse:MouseCollision;
		private var vector:Pivot3D;
		private var model:Pivot3D;
		private var lines:Lines3D;
		
		public function Test12_MousePaint_Extended() 
		{
			scene = new Viewer3D( this );			
			model = scene.addChildFromFile( "mouse.f3d" );
			vector = scene.addChildFromFile( "vector.f3d" );
			scene.addEventListener( Scene3D.COMPLETE_EVENT, completeEvent );
		}
		
		private function completeEvent(e:Event):void 
		{
			lines = new Lines3D();
			lines.parent = scene;
			
			mouse = new MouseCollision();
			mouse.addCollisionWith( model );
			
			scene.ambientColor = new Vector3D( 0.3, 0.3, 0.3 );
			scene.addEventListener( Scene3D.RENDER_EVENT, renderEvent );
		}
		
		private function renderEvent(e:Event):void 
		{
			if ( mouse.test( Input3D.mouseX, Input3D.mouseY ) )
			{
				// gets the first mouse collision info.
				var info:CollisionInfo = mouse.data[0];
				
				// access to the fisrt texture of the firts material.
				var texture:Texture3D = info.mesh.materials[0].textures[0];
				
				// the uv coords, are mapped from 0 to 1, so we need to multiply by the size of the texture.
				var u:Number = info.u * texture.bmp.width;
				var v:Number = info.v * texture.bmp.height;
				
				// draw some square over the texture at UV point.
				texture.bmp.fillRect( new Rectangle( u - 5, v - 5, 10, 10 ), Math.random() * 0xffffff );
				
				// because we did some changes on the texture, we need to
				// reupload again to the graphics card.
				texture.upload();
				
				/// additionaly, we align a 3d object to the point and normal of collision.
				vector.setPosition( info.point.x, info.point.y, info.point.z );
				vector.setNormalOrientation( info.normal, 0.3 );
				
				// get the vector pivot up/normal direction.
				var direction:Vector3D = vector.getUp();
				
				// begin dra the line.
				lines.clear();
				lines.lineStyle( 1, 0xff0000 );
				// starts from the vector pivot position.
				lines.moveTo( vector.x, vector.y, vector.z );
				// to, vector position plus direction * any value.
				lines.lineTo( vector.x + direction.x * 1000,
							  vector.y + direction.y * 1000,
							  vector.z + direction.z * 1000 );
				
				// access to the ray instance used by MouseCollision.
				// we can create a new instance of RayCollision, but in this case we can reuse 
				// the same instance.
				if ( mouse.ray.test( vector.getPosition(), direction ) )
				{
					trace( mouse.data[0].mesh.name );
				}
			}
		}		
	}
}